package com.jjiang.bbmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jjiang.bbmall.cart.feign.ProductFeignService;
import com.jjiang.bbmall.cart.interceptor.CartInterceptor;
import com.jjiang.bbmall.cart.service.CartService;
import com.jjiang.bbmall.cart.to.UserInfoTo;
import com.jjiang.bbmall.cart.vo.Cart;
import com.jjiang.bbmall.cart.vo.CartItem;
import com.jjiang.bbmall.cart.vo.SkuInfoVo;
import com.jjiang.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private static final String CART_PREFIX = "bbmall:cart:";


    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String find = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(find)) {
            // 购物车中有此商品，修改数量即可
            CartItem cartItem = JSON.parseObject(find, CartItem.class);
            if (cartItem != null) {
                cartItem.setCount(cartItem.getCount() + num);
            } else {
                System.out.println("修改商品数量失败！");
            }

            String cartItemString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemString);
            return cartItem;
        } else {
            // 如果之前没有此商品，新增商品
            CartItem cartItem = new CartItem();
            // 1.远程查询skuId对应的信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    // 调用成功
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItem.setCount(num);
                    cartItem.setImage(skuInfo.getSkuDefaultImg());
                    cartItem.setTitle(skuInfo.getSkuTitle());
                    cartItem.setPrice(skuInfo.getPrice());
                    cartItem.setSkuId(skuInfo.getSkuId());
                } else {
                    System.out.println("调用【R r = productFeignService.info(skuId);】失败");
                }
            }, executor);
            // 2. 远程查询sku组合信息
            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                cartItem.setSkuAttr(productFeignService.getSkuSaleAttrValues(skuId));
            }, executor);

            // 3. 等待1，2任务完成后，存储到redis中
            try {
                CompletableFuture.allOf(getSkuInfoTask, getSkuAttrTask).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            String cartItemString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemString);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(result, CartItem.class);
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        // 区分是登录还是未登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 已经登录
            // 判断临时购物车的数据是否进行了合并
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            if (cartItems != null && cartItems.size() != 0) {
                // 临时购物车有数据，需要进行合并
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 清除临时购物车的数据
                clearCart(cartKey);
            }
            // 再对登录后的购物车进行查询【包含合并过来的临时购物车数据】
            String cartId = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItemsByCartId = getCartItems(cartId);
            cart.setItems(cartItemsByCartId);

        } else {
            // 未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? Boolean.TRUE : Boolean.FALSE);
        String string = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), string);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        // 1.获取原本信息
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String string = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), string);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> currentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            // 获取被选中的购物项
            List<CartItem> collect = cartItems.stream().filter(CartItem::getCheck).map(item -> {
                // 更新为最新价格
                R r = productFeignService.getPrice(item.getSkuId());
                if (r.getCode() == 0) {
                    item.setPrice(r.getData(new TypeReference<BigDecimal>() {
                    }));
                }else{
                    item.setPrice(new BigDecimal("0"));
                }
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1. 检查用户是否登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 1.1 已经登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 1.2 未登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 2.加入购物车
        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        List<CartItem> collect = null;
        if (values != null && values.size() != 0) {
            // 遍历数据
            collect = values.stream().map((obj) -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return collect;
    }
}
